<!--
 * @FilePath: /web-vue/src/views/SysUser/registerForm.vue
 * @Description: 【系统用户】新增表单
-->
<template>
  <div>
    <!-- 弹出层-表单 -->
    <el-dialog
      class="add-dialog"
      title="欢迎注册本系统，请根据提示填写以下信息"
      :visible.sync="visible"
      :confirmLoading="confirmLoading"
      top="7vh"
      append-to-body
    >
      <el-form
        :model="addForm"
        :rules="rules"
        ref="addForm"
        status-icon
        label-width="120px"
        style="width: 100%"
        class="layer-form-style"
      >
        <el-form-item label="用户名：" prop="username" size="mini">
          <el-input
            v-model="addForm.username"
            placeholder="请输入用户名"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="密码：" prop="password" size="mini">
          <el-input
            type="password"
            v-model="addForm.password"
            placeholder="请输入密码"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="姓名：" prop="realName" size="mini">
          <el-input
            v-model="addForm.realName"
            placeholder="请输入姓名"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="性别：" prop="sex" size="mini">
          <el-radio-group v-model="addForm.sex">
            <el-radio label="1">男</el-radio>
            <el-radio label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="手机号：" prop="phone" size="mini">
          <el-input
            v-model="addForm.phone"
            placeholder="请输入手机号"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="电子邮箱：" prop="email" size="mini">
          <el-input
            v-model="addForm.email"
            placeholder="请输入电子邮箱"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="身份类型：" prop="roleIds" size="mini">
          <el-select
            v-model="addForm.roleIds"
            filterable
            clearable
            placeholder="请选择你注册的身份类型"
            style="width: 99%"
          >
            <el-option label="我是房东" :value="5"> </el-option>
            <el-option label="我是租客" :value="7"> </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          icon="el-icon-finished"
          @click="handleSubmit()"
          >保存
        </el-button>
        <el-button icon="el-icon-refresh-left" @click="handleCancel()"
          >取消
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
const dateTimePickerOption = {
  shortcuts: [
    {
      text: "今天",
      onClick(picker) {
        picker.$emit("pick", new Date());
      },
    },
    {
      text: "昨天",
      onClick(picker) {
        const date = new Date();
        date.setTime(date.getTime() - 3600 * 1000 * 24);
        picker.$emit("pick", date);
      },
    },
    {
      text: "一周前",
      onClick(picker) {
        const date = new Date();
        date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
        picker.$emit("pick", date);
      },
    },
  ],
};
// 正则
// 手机号
const phoneReg = /^((13[0-9])|(14[0-9])|(15[0-9])|(17[0-9])|(18[0-9]))\d{8}$/;
// 邮箱号
const emailReg =
  /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/;

// 手机号校验器
const phoneValidator = (rule, value, callback) => {
  if (phoneReg.test(value)) {
    callback();
  } else {
    callback(new Error("请输入正确格式的手机号！"));
  }
};
// 邮箱校验器
const emailValidator = (rule, value, callback) => {
  if (emailReg.test(value)) {
    callback();
  } else {
    callback(new Error("请输入正确格式的邮箱格式！"));
  }
};

export default {
  props: ["roleList"],
  data() {
    return {
      visible: false,
      confirmLoading: false,
      addForm: {
        username: null,
        password: null,
        realName: null,
        sex: null,
        duty: null,
        phone: null,
        email: null,
        roleIds: null,
        deptId: null,
      },
      // 表单校验规则
      rules: {
        username: [
          {
            required: true,
            message: "用户名不能为空！",
            trigger: "blur",
          },
        ],
        realName: [
          {
            required: true,
            message: "姓名不能为空！",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "密码不能为空！",
            trigger: "blur",
          },
        ],
        phone: [{ validator: phoneValidator, trigger: "blur" }],
        email: [{ validator: emailValidator, trigger: "blur" }],
      },
      // 日期选择快捷方式
      pickerOptions: dateTimePickerOption,
      switchBtn: true,
    };
  },

  methods: {
    // 打开【系统用户】表单新增窗口
    openAddForm(isShow) {
      this.visible = isShow;
    },

    // 关闭【系统用户】表单新增窗口
    handleCancel() {
      this.visible = false;
      this.$refs["addForm"].resetFields();
    },

    // 提交
    handleSubmit() {
      this.$refs["addForm"].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            target: document.querySelector(".add-dialog"),
            lock: true,
            text: "正在保存，请耐心等待！",
          });

          let vueIns = this;
          // 请求参数
          let param = Object.assign({}, this.addForm);
          param["roleIds"] = [this.addForm.roleIds];
          // 发起请求
          this.$api
            .addSysUser(param)
            .then((res) => {
              loading.close();
              let { status, message, data } = res.data; // 响应数据
              if (status == 200) {
                this.$emit("afterSubmit");
                this.handleCancel();
                // 提示信息
                this.$message({
                  type: "success",
                  message: `操作成功！已新增【系统用户】!${message}`,
                  duration: 1680,
                });
              } else if (status == 403) {
                this.$message({
                  message: `权限不足！${message}`,
                  type: "error",
                  center: true,
                  duration: 1680,
                });
                // this.$router.push("/login");
              } else {
                this.$alert(`操作失败！${message}`, "【系统用户】新增", {
                  type: "error",
                  confirmButtonText: "确定",
                  callback: (action) => {},
                });
              }
            })
            .catch(function (err) {
              loading.close();
              vueIns.visible = false;
              console.log(`【系统用户】新增接口发生错误：${err}`);
            });
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
// 表单布局样式
@import "@/assets/css/form-layout.scss";
</style>
